<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <title>Per-Object Motion Blur Shader — Alien.js</title>

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto+Mono">
    <link rel="stylesheet" href="../assets/css/style.css">

    <script type="module">
        import { AdditiveBlending, BloomCompositeMaterial, Color, ColorManagement, DepthMaterial, DisplayOptions, EnvironmentTextureLoader, Group, HemisphereLight, IcosahedronGeometry, ImageBitmapLoaderThread, LinearSRGBColorSpace, LuminosityMaterial, MathUtils, Mesh, MeshBasicMaterial, MeshMatcapMaterial, MeshStandardMaterial, MotionBlur, MotionBlurCompositeMaterial, NoBlending, NormalMaterial, OrbitControls, OrthographicCamera, PanelItem, PerspectiveCamera, RepeatWrapping, Scene, SceneCompositeDistortionMaterial, SphereGeometry, TextureLoader, UI, UnrealBloomBlurMaterial, Vector2, WebGLRenderTarget, WebGLRenderer, getFullscreenTriangle, getKeyByValue, ticker } from '../../build/alien.three.js';

        const layers = {
            default: 0,
            velocity: 1
        };

        const params = {
            animate: true,
            speed: 20
        };

        class Ball extends Group {
            constructor() {
                super();

                this.frameRotation = 0;
                this.position.x = 3;
                this.position.z = 3;
            }

            async initMesh() {
                const { anisotropy, loadTexture } = WorldController;

                const geometry = new IcosahedronGeometry(0.5, 12);

                // Second set of UVs for aoMap and lightMap
                // https://threejs.org/docs/#api/en/materials/MeshStandardMaterial.aoMap
                geometry.attributes.uv1 = geometry.attributes.uv;

                // Textures
                const [map, normalMap, ormMap, thicknessMap] = await Promise.all([
                    // loadTexture('uv.jpg'),
                    loadTexture('pbr/pitted_metal_basecolor.jpg'),
                    loadTexture('pbr/pitted_metal_normal.jpg'),
                    // https://occlusion-roughness-metalness.glitch.me/
                    loadTexture('pbr/pitted_metal_orm.jpg'),
                    loadTexture('pbr/pitted_metal_height.jpg')
                ]);

                map.anisotropy = anisotropy;
                map.wrapS = RepeatWrapping;
                map.wrapT = RepeatWrapping;
                map.repeat.set(2, 1);

                normalMap.anisotropy = anisotropy;
                normalMap.wrapS = RepeatWrapping;
                normalMap.wrapT = RepeatWrapping;
                normalMap.repeat.set(2, 1);

                ormMap.anisotropy = anisotropy;
                ormMap.wrapS = RepeatWrapping;
                ormMap.wrapT = RepeatWrapping;
                ormMap.repeat.set(2, 1);

                thicknessMap.anisotropy = anisotropy;
                thicknessMap.wrapS = RepeatWrapping;
                thicknessMap.wrapT = RepeatWrapping;
                thicknessMap.repeat.set(2, 1);

                const material = new MeshStandardMaterial({
                    color: new Color().offsetHSL(0, 0, -0.65),
                    emissive: new Color(0xff0000),
                    metalness: 1.7,
                    roughness: 1.5,
                    map,
                    metalnessMap: ormMap,
                    roughnessMap: ormMap,
                    aoMap: ormMap,
                    aoMapIntensity: 1,
                    normalMap,
                    normalScale: new Vector2(3, 3)
                });

                // Second channel for aoMap and lightMap
                // https://threejs.org/docs/#api/en/materials/MeshStandardMaterial.aoMap
                material.aoMap.channel = 1;

                const mesh = new Mesh(geometry, material);
                mesh.layers.enable(layers.velocity);
                this.add(mesh);
            }

            // Public methods

            update = () => {
                this.frameRotation -= 0.01 * params.speed;
                this.position.x = 3 * Math.sin(this.frameRotation);
                this.position.z = 3 * Math.cos(this.frameRotation);
            };

            ready = () => this.initMesh();
        }

        class Sphere extends Group {
            constructor() {
                super();
            }

            async initMesh() {
                const { anisotropy, loadTexture } = WorldController;

                const geometry = new SphereGeometry(1, 80, 80);

                // Second set of UVs for aoMap and lightMap
                // https://threejs.org/docs/#api/en/materials/MeshStandardMaterial.aoMap
                geometry.attributes.uv1 = geometry.attributes.uv;

                // Textures
                const [map, normalMap, ormMap] = await Promise.all([
                    // loadTexture('uv.jpg'),
                    loadTexture('pbr/pitted_metal_basecolor.jpg'),
                    loadTexture('pbr/pitted_metal_normal.jpg'),
                    // https://occlusion-roughness-metalness.glitch.me/
                    loadTexture('pbr/pitted_metal_orm.jpg')
                ]);

                map.anisotropy = anisotropy;
                map.wrapS = RepeatWrapping;
                map.wrapT = RepeatWrapping;
                map.repeat.set(2, 1);

                normalMap.anisotropy = anisotropy;
                normalMap.wrapS = RepeatWrapping;
                normalMap.wrapT = RepeatWrapping;
                normalMap.repeat.set(2, 1);

                ormMap.anisotropy = anisotropy;
                ormMap.wrapS = RepeatWrapping;
                ormMap.wrapT = RepeatWrapping;
                ormMap.repeat.set(2, 1);

                const material = new MeshStandardMaterial({
                    color: new Color(0x060606),
                    metalness: 1,
                    roughness: 1,
                    map,
                    metalnessMap: ormMap,
                    roughnessMap: ormMap,
                    aoMap: ormMap,
                    aoMapIntensity: 1,
                    normalMap,
                    normalScale: new Vector2(1, 1)
                });

                // Second channel for aoMap and lightMap
                // https://threejs.org/docs/#api/en/materials/MeshStandardMaterial.aoMap
                material.aoMap.channel = 1;

                const mesh = new Mesh(geometry, material);
                mesh.layers.enable(layers.velocity);
                this.add(mesh);
            }

            // Public methods

            ready = () => this.initMesh();
        }

        class SceneView extends Group {
            constructor() {
                super();

                this.visible = false;

                this.initViews();
            }

            initViews() {
                this.sphere = new Sphere();
                this.add(this.sphere);

                this.ball = new Ball();
                this.add(this.ball);
            }

            // Public methods

            resize = () => {
            };

            update = () => {
                this.ball.update();
            };

            ready = () => Promise.all([
                this.sphere.ready(),
                this.ball.ready()
            ]);
        }

        class SceneController {
            static init(view) {
                this.view = view;

                this.animatedOneFramePast = false;
            }

            // Public methods

            static resize = (width, height) => {
                this.view.resize(width, height);
            };

            static update = () => {
                if (!this.view.visible) {
                    return;
                }

                if (params.animate || !this.animatedOneFramePast) {
                    this.view.update();

                    this.animatedOneFramePast = !params.animate;
                }
            };

            static animateIn = () => {
                this.view.visible = true;
            };

            static ready = () => this.view.ready();
        }

        class PanelController {
            static init(view, ui) {
                this.view = view;
                this.ui = ui;

                this.initPanel();
            }

            static initPanel() {
                const { motionBlur, luminosityMaterial, bloomCompositeMaterial, compositeMaterial } = RenderManager;

                const animateOptions = {
                    Off: false,
                    Animate: true
                };

                const items = [
                    {
                        name: 'FPS'
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'list',
                        list: DisplayOptions,
                        value: getKeyByValue(DisplayOptions, RenderManager.display),
                        callback: value => {
                            RenderManager.display = DisplayOptions[value];
                        }
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'slider',
                        name: 'Speed',
                        min: 0,
                        max: 100,
                        step: 0.1,
                        value: params.speed,
                        callback: value => {
                            params.speed = value;
                        }
                    },
                    {
                        type: 'list',
                        list: animateOptions,
                        value: getKeyByValue(animateOptions, params.animate),
                        callback: value => {
                            params.animate = animateOptions[value];
                            motionBlur.saveState = params.animate;
                        }
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'slider',
                        name: 'Interp',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: motionBlur.interpolateGeometry,
                        callback: value => {
                            motionBlur.interpolateGeometry = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Smear',
                        min: 0,
                        max: 4,
                        step: 0.02,
                        value: motionBlur.smearIntensity,
                        callback: value => {
                            motionBlur.smearIntensity = value;
                        }
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'slider',
                        name: 'Thresh',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: luminosityMaterial.uniforms.uThreshold.value,
                        callback: value => {
                            luminosityMaterial.uniforms.uThreshold.value = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Smooth',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: luminosityMaterial.uniforms.uSmoothing.value,
                        callback: value => {
                            luminosityMaterial.uniforms.uSmoothing.value = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Strength',
                        min: 0,
                        max: 2,
                        step: 0.01,
                        value: RenderManager.bloomStrength,
                        callback: value => {
                            RenderManager.bloomStrength = value;
                            bloomCompositeMaterial.uniforms.uBloomFactors.value = RenderManager.bloomFactors();
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Radius',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: RenderManager.bloomRadius,
                        callback: value => {
                            RenderManager.bloomRadius = value;
                            bloomCompositeMaterial.uniforms.uBloomFactors.value = RenderManager.bloomFactors();
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Chroma',
                        min: 0,
                        max: 10,
                        step: 0.1,
                        value: compositeMaterial.uniforms.uBloomDistortion.value,
                        callback: value => {
                            compositeMaterial.uniforms.uBloomDistortion.value = value;
                        }
                    }
                ];

                items.forEach(data => {
                    this.ui.addPanel(new PanelItem(data));
                });
            }
        }

        // Based on https://github.com/gkjohnson/threejs-sandbox/tree/master/motionBlurPass
        // Based on https://github.com/gkjohnson/threejs-sandbox/tree/master/shader-replacement

        const BlurDirectionX = new Vector2(1, 0);
        const BlurDirectionY = new Vector2(0, 1);

        class RenderManager {
            static init(renderer, scene, camera) {
                this.renderer = renderer;
                this.scene = scene;
                this.camera = camera;

                // Unreal bloom
                this.luminosityThreshold = 0.1;
                this.luminositySmoothing = 1;
                this.bloomStrength = 0.3;
                this.bloomRadius = 0.2;
                this.bloomDistortion = 1;

                // Debug
                this.display = DisplayOptions.Default;

                this.enabled = true;

                this.initRenderer();
            }

            static initRenderer() {
                const { screenTriangle, textureLoader, getTexture } = WorldController;

                // Manually clear
                this.renderer.autoClear = false;

                // Clear colors
                this.clearColor = new Color(0, 0, 0);
                this.currentClearColor = new Color();

                // Fullscreen triangle
                this.screenCamera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
                this.screen = new Mesh(screenTriangle);
                this.screen.frustumCulled = false;

                // Render targets
                this.renderTargetA = new WebGLRenderTarget(1, 1, {
                    depthBuffer: false
                });

                this.renderTargetB = this.renderTargetA.clone();

                this.renderTargetBright = this.renderTargetA.clone();
                this.renderTargetsHorizontal = [];
                this.renderTargetsVertical = [];
                this.nMips = 5;

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.renderTargetsHorizontal.push(this.renderTargetA.clone());
                    this.renderTargetsVertical.push(this.renderTargetA.clone());
                }

                this.renderTargetA.depthBuffer = true;

                // Motion blur
                this.motionBlur = new MotionBlur(this.renderer, this.scene, this.camera, layers.velocity);

                this.motionBlurCompositeMaterial = new MotionBlurCompositeMaterial(textureLoader, {
                    blueNoisePath: 'blue_noise.png'
                });
                this.motionBlurCompositeMaterial.uniforms.tVelocity.value = this.motionBlur.renderTarget.texture;

                // Luminosity high pass material
                this.luminosityMaterial = new LuminosityMaterial();
                this.luminosityMaterial.uniforms.uThreshold.value = this.luminosityThreshold;
                this.luminosityMaterial.uniforms.uSmoothing.value = this.luminositySmoothing;

                // Separable Gaussian blur materials
                this.blurMaterials = [];

                const kernelSizeArray = [3, 5, 7, 9, 11];

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.blurMaterials.push(new UnrealBloomBlurMaterial(kernelSizeArray[i]));
                }

                // Unreal bloom composite material
                this.bloomCompositeMaterial = new BloomCompositeMaterial();
                this.bloomCompositeMaterial.uniforms.tBlur1.value = this.renderTargetsVertical[0].texture;
                this.bloomCompositeMaterial.uniforms.tBlur2.value = this.renderTargetsVertical[1].texture;
                this.bloomCompositeMaterial.uniforms.tBlur3.value = this.renderTargetsVertical[2].texture;
                this.bloomCompositeMaterial.uniforms.tBlur4.value = this.renderTargetsVertical[3].texture;
                this.bloomCompositeMaterial.uniforms.tBlur5.value = this.renderTargetsVertical[4].texture;
                this.bloomCompositeMaterial.uniforms.uBloomFactors.value = this.bloomFactors();

                // Composite material
                this.compositeMaterial = new SceneCompositeDistortionMaterial({ dithering: true });
                this.compositeMaterial.uniforms.uBloomDistortion.value = this.bloomDistortion;

                // Debug materials
                this.blackoutMaterial = new MeshBasicMaterial({ color: 0x000000 });
                this.matcap1Material = new MeshMatcapMaterial({ matcap: getTexture('matcaps/040full.jpg') });
                this.matcap2Material = new MeshMatcapMaterial({ matcap: getTexture('matcaps/defaultwax.jpg') });
                this.normalMaterial = new NormalMaterial();
                this.depthMaterial = new DepthMaterial();
            }

            static bloomFactors() {
                const bloomFactors = [1, 0.8, 0.6, 0.4, 0.2];

                for (let i = 0, l = this.nMips; i < l; i++) {
                    const factor = bloomFactors[i];
                    bloomFactors[i] = this.bloomStrength * MathUtils.lerp(factor, 1.2 - factor, this.bloomRadius);
                }

                return bloomFactors;
            }

            static rendererState() {
                this.currentOverrideMaterial = this.scene.overrideMaterial;
                this.currentBackground = this.scene.background;
                this.renderer.getClearColor(this.currentClearColor);
                this.currentClearAlpha = this.renderer.getClearAlpha();
            }

            static restoreRendererState() {
                this.scene.overrideMaterial = this.currentOverrideMaterial;
                this.scene.background = this.currentBackground;
                this.renderer.setClearColor(this.currentClearColor, this.currentClearAlpha);
            }

            // Public methods

            static resize = (width, height, dpr) => {
                this.renderer.setPixelRatio(dpr);
                this.renderer.setSize(width, height);

                width = Math.round(width * dpr);
                height = Math.round(height * dpr);

                this.renderTargetA.setSize(width, height);
                this.renderTargetB.setSize(width, height);

                this.motionBlur.setSize(width, height);

                // Unreal bloom
                width = Math.round(width / 2);
                height = Math.round(height / 2);

                this.renderTargetBright.setSize(width, height);

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.renderTargetsHorizontal[i].setSize(width, height);
                    this.renderTargetsVertical[i].setSize(width, height);

                    this.blurMaterials[i].uniforms.uResolution.value.set(width, height);

                    width = Math.round(width / 2);
                    height = Math.round(height / 2);
                }
            };

            static update = () => {
                const renderer = this.renderer;
                const scene = this.scene;
                const camera = this.camera;

                if (!this.enabled) {
                    renderer.setRenderTarget(null);
                    renderer.clear();
                    renderer.render(scene, camera);
                    return;
                }

                const renderTargetA = this.renderTargetA;
                const renderTargetB = this.renderTargetB;
                const renderTargetBright = this.renderTargetBright;
                const renderTargetsHorizontal = this.renderTargetsHorizontal;
                const renderTargetsVertical = this.renderTargetsVertical;

                // Renderer state
                this.rendererState();

                // Scene layer
                camera.layers.set(layers.default);

                renderer.setRenderTarget(renderTargetA);
                renderer.clear();
                renderer.render(scene, camera);

                // Post-processing
                scene.background = null;
                renderer.setClearColor(this.clearColor, 1);

                // Debug override material passes (render to screen)
                if (this.display === DisplayOptions.Depth) {
                    scene.overrideMaterial = this.depthMaterial;
                    renderer.setRenderTarget(null);
                    renderer.clear();
                    renderer.render(scene, camera);
                    this.restoreRendererState();
                    return;
                } else if (this.display === DisplayOptions.Geometry) {
                    scene.overrideMaterial = this.normalMaterial;
                    renderer.setRenderTarget(null);
                    renderer.clear();
                    renderer.render(scene, camera);
                    this.restoreRendererState();
                    return;
                } else if (this.display === DisplayOptions.Matcap1) {
                    scene.overrideMaterial = this.matcap1Material;
                    renderer.setRenderTarget(null);
                    renderer.clear();
                    renderer.render(scene, camera);
                    this.restoreRendererState();
                    return;
                } else if (this.display === DisplayOptions.Matcap2) {
                    scene.overrideMaterial = this.matcap2Material;
                    renderer.setRenderTarget(null);
                    renderer.clear();
                    renderer.render(scene, camera);
                    this.restoreRendererState();
                    return;
                }

                // Motion blur layer
                camera.layers.set(layers.velocity);

                if (this.display === DisplayOptions.Velocity) {
                    // Debug pass (render to screen)
                    this.motionBlur.update(null);
                    this.restoreRendererState();
                    return;
                } else {
                    this.motionBlur.update();
                }

                this.motionBlurCompositeMaterial.uniforms.tMap.value = renderTargetA.texture;
                this.screen.material = this.motionBlurCompositeMaterial;
                renderer.setRenderTarget(renderTargetB);
                renderer.clear();
                renderer.render(this.screen, this.screenCamera);

                // Extract bright areas
                this.luminosityMaterial.uniforms.tMap.value = renderTargetB.texture;

                if (this.display === DisplayOptions.Luma) {
                    // Debug pass (render to screen)
                    this.screen.material = this.blackoutMaterial;
                    renderer.setRenderTarget(null);
                    renderer.clear();
                    renderer.render(this.screen, this.screenCamera);
                    this.screen.material = this.luminosityMaterial;
                    this.screen.material.blending = AdditiveBlending;
                    renderer.render(this.screen, this.screenCamera);
                    this.screen.material.blending = NoBlending;
                    this.restoreRendererState();
                    return;
                } else {
                    this.screen.material = this.luminosityMaterial;
                    renderer.setRenderTarget(renderTargetBright);
                    renderer.clear();
                    renderer.render(this.screen, this.screenCamera);
                }

                // Blur all the mips progressively
                let inputRenderTarget = renderTargetBright;

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.screen.material = this.blurMaterials[i];

                    this.blurMaterials[i].uniforms.tMap.value = inputRenderTarget.texture;
                    this.blurMaterials[i].uniforms.uDirection.value = BlurDirectionX;
                    renderer.setRenderTarget(renderTargetsHorizontal[i]);
                    renderer.clear();
                    renderer.render(this.screen, this.screenCamera);

                    this.blurMaterials[i].uniforms.tMap.value = this.renderTargetsHorizontal[i].texture;
                    this.blurMaterials[i].uniforms.uDirection.value = BlurDirectionY;
                    renderer.setRenderTarget(renderTargetsVertical[i]);
                    renderer.clear();
                    renderer.render(this.screen, this.screenCamera);

                    inputRenderTarget = renderTargetsVertical[i];
                }

                // Composite all the mips
                this.screen.material = this.bloomCompositeMaterial;

                if (this.display === DisplayOptions.Bloom) {
                    // Debug pass (render to screen)
                    renderer.setRenderTarget(null);
                    renderer.clear();
                    renderer.render(this.screen, this.screenCamera);
                    this.restoreRendererState();
                    return;
                } else {
                    renderer.setRenderTarget(renderTargetsHorizontal[0]);
                    renderer.clear();
                    renderer.render(this.screen, this.screenCamera);
                }

                // Composite pass (render to screen)
                this.compositeMaterial.uniforms.tScene.value = renderTargetB.texture;
                this.compositeMaterial.uniforms.tBloom.value = renderTargetsHorizontal[0].texture;
                this.screen.material = this.compositeMaterial;
                renderer.setRenderTarget(null);
                renderer.clear();
                renderer.render(this.screen, this.screenCamera);

                // Restore renderer settings
                this.restoreRendererState();
            };
        }

        class WorldController {
            static init() {
                this.initWorld();
                this.initLights();
                this.initLoaders();
                this.initEnvironment();
                this.initControls();

                this.addListeners();
            }

            static initWorld() {
                this.renderer = new WebGLRenderer({
                    powerPreference: 'high-performance',
                    antialias: true
                });

                // Output canvas
                this.element = this.renderer.domElement;

                // Disable color management
                ColorManagement.enabled = false;
                this.renderer.outputColorSpace = LinearSRGBColorSpace;

                // 3D scene
                this.scene = new Scene();
                this.scene.background = new Color(0x060606);
                this.camera = new PerspectiveCamera(30);
                this.camera.near = 0.5;
                this.camera.far = 40;
                this.camera.position.z = 8;
                this.camera.lookAt(this.scene.position);

                // Global geometries
                this.screenTriangle = getFullscreenTriangle();

                // Global uniforms
                this.resolution = { value: new Vector2() };
                this.texelSize = { value: new Vector2() };
                this.aspect = { value: 1 };
                this.time = { value: 0 };
                this.frame = { value: 0 };

                // Global settings
                this.anisotropy = this.renderer.capabilities.getMaxAnisotropy();
            }

            static initLights() {
                this.scene.add(new HemisphereLight(0x606060, 0x404040, 3));
            }

            static initLoaders() {
                this.textureLoader = new TextureLoader();
                this.textureLoader.setPath('../assets/textures/');

                this.environmentLoader = new EnvironmentTextureLoader(this.renderer);
                this.environmentLoader.setPath('../assets/textures/env/');
            }

            static async initEnvironment() {
                this.scene.environment = await this.loadEnvironmentTexture('jewelry_black_contrast.jpg');
                this.scene.environmentIntensity = 0.5;
            }

            static initControls() {
                this.controls = new OrbitControls(this.camera, this.renderer.domElement);
                this.controls.enableDamping = true;
            }

            static addListeners() {
                this.renderer.domElement.addEventListener('touchstart', this.onTouchStart);
            }

            // Event handlers

            static onTouchStart = e => {
                e.preventDefault();
            };

            // Public methods

            static resize = (width, height, dpr) => {
                this.camera.aspect = width / height;
                this.camera.updateProjectionMatrix();

                if (width < height) {
                    this.camera.position.z = 10;
                } else {
                    this.camera.position.z = 8;
                }

                width = Math.round(width * dpr);
                height = Math.round(height * dpr);

                this.resolution.value.set(width, height);
                this.texelSize.value.set(1 / width, 1 / height);
                this.aspect.value = width / height;
            };

            static update = (time, delta, frame) => {
                this.time.value = time;
                this.frame.value = frame;

                if (this.controls && this.controls.enabled) {
                    this.controls.update();
                }
            };

            static ready = () => Promise.all([
                this.textureLoader.ready(),
                this.environmentLoader.ready()
            ]);

            // Global handlers

            static getTexture = (path, callback) => this.textureLoader.load(path, callback);

            static loadTexture = path => this.textureLoader.loadAsync(path);

            static loadEnvironmentTexture = path => this.environmentLoader.loadAsync(path);
        }

        class App {
            static async init() {
                this.initThread();
                this.initWorld();
                this.initViews();
                this.initControllers();

                this.addListeners();
                this.onResize();

                await SceneController.ready();
                await WorldController.ready();

                this.initPanel();

                SceneController.animateIn();
            }

            static initThread() {
                ImageBitmapLoaderThread.init();
            }

            static initWorld() {
                WorldController.init();
                document.body.appendChild(WorldController.element);
            }

            static initViews() {
                this.view = new SceneView();
                WorldController.scene.add(this.view);

                this.ui = new UI({ fps: true });
                this.ui.animateIn();
                document.body.appendChild(this.ui.element);
            }

            static initControllers() {
                const { renderer, scene, camera } = WorldController;

                SceneController.init(this.view);
                RenderManager.init(renderer, scene, camera);
            }

            static initPanel() {
                PanelController.init(this.view, this.ui);
            }

            static addListeners() {
                window.addEventListener('resize', this.onResize);
                ticker.add(this.onUpdate);
                ticker.start();
            }

            // Event handlers

            static onResize = () => {
                const width = document.documentElement.clientWidth;
                const height = document.documentElement.clientHeight;
                const dpr = window.devicePixelRatio;

                WorldController.resize(width, height, dpr);
                SceneController.resize(width, height);
                RenderManager.resize(width, height, dpr);
            };

            static onUpdate = (time, delta, frame) => {
                WorldController.update(time, delta, frame);
                SceneController.update();
                RenderManager.update(time, delta, frame);
                this.ui.update();
            };
        }

        App.init();
    </script>
</head>
<body>
</body>
</html>
